<?php

class Application_Model_GroupMapper {

    protected $_dbTable;

    public function getDbTable() {
        if (null === $this->_dbTable) {
            $this->setDbTable('Application_Model_DbTable_GroupModel');
        }
        return $this->_dbTable;
    }

    public function setDbTable($dbTable) {
        if (is_string($dbTable)) {
            $dbTable = new $dbTable();
        }
        if (!$dbTable instanceof Zend_Db_Table_Abstract) {
            throw new Exception('Ungueltige Gateway-Klasse fuer Tabellendaten');
        }
        $this->_dbTable = $dbTable;
    }

    public function save(Application_Model_GroupModel $group) {
        $data = array(
            'id' => $group->getId(),
            'name' => $group->getName(),
            'password' => $group->getPassword(),
        );
        if (null === $group->getId()) {
            unset($data['id']);

            $group->setId($this->getDbTable()->insert($data));
        } else {
            $this->getDbTable()->update($data, array('id = ?' => $data['id']));
        }
        return $this;
    }

    public function find($id, Application_Model_GroupModel $group) {
        $result = $this->getDbTable()->find($id);
        if (0 == count($result)) {
            return null;
        }
        $row = $result->current();
        $group->setId($row['id'])
                ->setName($row['name'])
                ->setpassword($row['password']);

        return $group;
    }

    public function fetchAll($where = null, $order = null, $count = null, $offset = null) {
        $resultSet = $this->getDbTable()->fetchAll($where, $order, $count, $offset);
        $entries = array();
        foreach ($resultSet as $row) {
            $entry = new Application_Model_GroupModel();
            $entry->setId($row['id'])
                    ->setName($row['name'])
                    ->setPassword($row['password']);
            $entries[] = $entry;
        }
        return $entries;
    }

    public function delete($groupId) {
        if ($groupId instanceof Application_Model_GroupModel) {
            $groupId = $groupId->id;
        }
        return $this->getDbTable()->delete(array('id = ?' => $groupId));
    }

}

